﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace GetComics.Silverlight
{
    public class SuperCanvas : Canvas
    {
        private double _deltaX, _deltaY;
        private bool _mouseCaptured;

        public SuperCanvas()
            : base()
        {
        }

        void element_MouseMove(object sender, MouseEventArgs e)
        {
            if (_mouseCaptured)
            {
                FrameworkElement el = (FrameworkElement)sender;
                if (el.Tag is IMovable)                
                    ((IMovable)el.Tag).Move(new Point(e.GetPosition(null).X - _deltaX, e.GetPosition(null).Y - _deltaY), el);
                
            }
        }

        void element_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            ((FrameworkElement)sender).ReleaseMouseCapture();
            _mouseCaptured = false;
        }

        void element_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            TranslateTransform trTrans = ((TransformGroup)((FrameworkElement)sender).RenderTransform).GetTransform<TranslateTransform>();
            _deltaX = e.GetPosition(null).X - trTrans.X;
            _deltaY = e.GetPosition(null).Y - trTrans.Y;
            CaptureMouse();
            _mouseCaptured = true;
        }

        public void AddDragable(FrameworkElement element)
        {
            element.MouseLeftButtonDown += new MouseButtonEventHandler(element_MouseLeftButtonDown);
            element.MouseLeftButtonUp += new MouseButtonEventHandler(element_MouseLeftButtonUp);
            element.MouseMove += new MouseEventHandler(element_MouseMove);
            this.Children.Add(element);
        }
    }
}
